<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

if($USER->checkAdminPermission('core', 'perm_edit_page') || $USER->checkAdminPerms('core', 'perm_create_page')){
    // permitted
}else{
    JFX::redirect($CONFIG->adminUrl);
}

$json = $_POST['data'];

$page = json_decode($json);

foreach($page->deletedBlocks as $k=>$v){
    $block = JFX_Block::getBlockById($v);
    $block->delete();
}

ob_start();
var_dump($page);
$string = ob_get_contents();
ob_end_clean();

$fh = fopen($CONFIG->baseDir.'/block-log.txt', 'w');
fwrite($fh, $string);
fclose($fh);

/*
echo '<pre>';
var_dump($_POST);
echo '</pre>';
*/

$pageid = (int) $page->pageid;

$this->updateContentLang('heading', $pageid, $page->details->title);


$elements = JFX_SavePage_SaveBlocks($page);

$res->status = 'OK';
$res->title = $pageid.'-'.$page->details->title;



while(ob_get_level()>0) ob_end_clean();

echo json_encode($res);

exit;




function JFX_SavePage_SaveBlocks($element){
    $DB = JFX::registry('db');
    $CONFIG = JFX::registry('config');
    $USER = JFX::registry('JFX_User');
    $elements = array();
    $parentId = $element->id;
    if($parentId == 'jfxpage-'.$element->pageid) $isPageParent = true;
    else $isPageParent = false;
    //$DB->debug(true);
    //$DB->showErrors(true);
    foreach($element->elements as $k=>$v){
        $elementId = $DB->escape($v->id);
        $bData = JFX::ArrayToObject($v->details);
        /*
        echo '<pre>';
        var_dump($bData);
        var_dump($v);
        echo '</pre>';
        */
         
        $block = new JFX_Block;
        if(!$block->loadById($v->id, $element->pageid, $USER->workspace)){
            // create a new block
            $block = JFX_Block::newModuleBlock($bData->module_key, $bData->module_action);
        };
        if(count($v->elements)>0){
            $block->elements = JFX_SavePage_SaveBlocks($v);
        };
        $bData->sorting = $k;
        $bData->workspace_id = $USER->workspace;

        if(false===$block->setDetails($bData)) die('error setting details');
        $block->save();
        $elements[] = $block;
    }
    //$DB->showErrors(false);
    return $elements;
    //$DB->debug(false);
    
}


